package com.platform.cdcs.activity;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.zxing.client.android.DecoderMode;
import com.platform.cdcs.R;
import com.platform.cdcs.adapter.ScanItemAdapter;
import com.platform.cdcs.fragment.ProductFragment;
import com.platform.cdcs.fragment.TicketDetailFragment;
import com.platform.cdcs.fragment.detail.ProductInfoFragment;
import com.platform.cdcs.fragment.detail.ProductListFragment;
import com.platform.cdcs.fragment.stock.AddProductFragment;
import com.platform.cdcs.model.InvoiceList;
import com.platform.cdcs.model.ProductList;
import com.platform.cdcs.model.RefershEvent;
import com.platform.cdcs.tool.CacheTool;
import com.platform.cdcs.tool.Constant;
import com.platform.cdcs.tool.FragmentUtil;
import com.platform.cdcs.tool.ViewTool;
import com.platform.cdcs.widget.CodeDemoWindow;
import com.platform.cdcs.widget.FormDialog;
import com.trueway.app.uilib.model.ChooseItem;
import com.trueway.app.uilib.tool.Utils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import de.greenrobot.event.EventBus;
import okhttp3.Call;

/**
 * Created by holytang on 2017/9/30.
 */
public class SearchScanActivity extends ScanBaseActivity {

    MenuItem titleItem;
    private int[] demo = new int[]{R.mipmap.unique_demo, R.mipmap.box_demo, R.mipmap.gs1_demo};
    private int position = 0;
    private TextView titleView;
    private String pos2Code1 = "", pos2Code2 = "";
    private String pos3Code1 = "", pos3Code2 = "", pos3Date = "";;
    private String pos1Code;
    private Handler mHandler;
    private View.OnClickListener tipListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (view.getId() == R.id.button2) {
                new CodeDemoWindow(getActivity()).setImg(demo[position - 1], view);
            } else {
                String[] forms = null;
                String title = null;
                int type = 0;
                if (position == 1) {
                    forms = new String[]{"唯一码"};
                    title = "唯一码";
                } else if (position == 2) {
                    forms = new String[]{"运单号", "箱号"};
                    title = "箱码";
                } else {
                    title = "GS1码";
                    type = 1;
                    forms = new String[]{"01-[GTIN]", "10-[批号]", "11-[生产日期]", "17-[失效日期]", "20-[变种]", "21-[唯一标识]"};
                }
                new FormDialog(getActivity(), new FormDialog.FormListener() {
                    @Override
                    public void okClick(String[] value) {
                        if (position == 1) {
                            pos1Code = value[0];
                            query();
                        } else if (position == 2) {
                            pos2Code1 = value[0];
                            pos2Code2 = value[1];
                            show(null);
                        } else {
                            pos3Code1 = value[0];
                            pos3Code2 = value[1];
                            show(value);
                        }
                    }
                }, title).addView(forms, type, "").show();
            }
        }
    };
    /**
     * 监听扫码数据的广播，当设置广播输出时作用该方法获取扫码数据
     */
    private BroadcastReceiver mResultReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if ("nlscan.action.SCANNER_RESULT".equals(action)) {
                final String scanResult_1 = intent.getStringExtra("SCAN_BARCODE1");
                final String scanResult_2 = intent.getStringExtra("SCAN_BARCODE2");
                final int barcodeType = intent.getIntExtra("SCAN_BARCODE_TYPE", -1); // -1:unknown
                final String scanStatus = intent.getStringExtra("SCAN_STATE");
                if ("ok".equals(scanStatus)) {
                    //成功
//                    System.out.println("==================::  "+scanResult_1);
                    scanResult(scanResult_1);
                    stopPDAScan();
                } else {
                    //失败如超时等
                }

            }
//            if(ScanManager.ACTION_SEND_SCAN_RESULT.equals(action)){
//                byte[] bvalue1=intent.getByteArrayExtra(ScanManager.EXTRA_SCAN_RESULT_ONE_BYTES);
//                byte[] bvalue2=intent.getByteArrayExtra(ScanManager.EXTRA_SCAN_RESULT_TWO_BYTES);
//                String svalue1=null;
//                String svalue2=null;
//                try {
//                    if(bvalue1!=null)
//                        svalue1=new String(bvalue1,"GBK");
//                    if(bvalue2!=null)
//                        svalue2=new String(bvalue1,"GBK");
//                    svalue1=svalue1==null?"":svalue1;
//                    svalue2=svalue2==null?"":svalue2;
////                    tv_broadcast_result.setText(svalue1+"\n"+svalue2);
//                } catch (Exception e) {
//                    e.printStackTrace();
////                    tv_broadcast_result.setText("data encode failed.");
//                }
//
//            }

        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver();
    }

    @Override
    protected void onPause() {
        super.onPause();
        unRegisterReceiver();
    }

    private void registerReceiver() {
        IntentFilter intFilter = new IntentFilter("nlscan.action.SCANNER_RESULT");
        registerReceiver(mResultReceiver, intFilter);
    }

    private void unRegisterReceiver() {
        try {
            unregisterReceiver(mResultReceiver);
        } catch (Exception e) {
        }
    }

    @Override
    protected void initLayout() {
        mHandler = new Handler();
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.stock_scan);
    }

    private void initTip(TextView textViews1, TextView textView2, String[] tip) {
        titleView.setText(Constant.SCAN_TITLES[position]);
        if (position == 0) {
            textViews1.setVisibility(View.GONE);
            textView2.setVisibility(View.GONE);
            changeScanMode(DecoderMode.Zxing);
        } else {
            textViews1.setVisibility(View.VISIBLE);
            textView2.setVisibility(View.VISIBLE);
            textViews1.setText(tip[0]);
            textView2.setText(tip[1]);
            changeScanMode(DecoderMode.Zbar);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (grantResults.length > 0 && requestCode == Constant.PERMISSION_CAMERA) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Intent intent = new Intent(this, SearchScanActivity.class);
                startActivity(intent);
                finish();
            } else {
                finish();
                Utils.showToast(getActivity(), "请先打开摄像头权限！");
            }
        }
    }

    @Override
    protected void initMenu(Menu menu) {
        titleItem = menu.add(0, 0, 0, "PDA扫码").setTitle("PDA扫码").setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem menuItem) {
                if (!pdaFlag) {
                    titleItem.setTitle("摄像头");
                    pdaFlag = true;
                    closeCamera();
                    mHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            PDAScan();
                        }
                    }, 500);
                } else {
                    stopPDAScan();
                    titleItem.setTitle("PDA扫码");
                    pdaFlag = false;
                    mHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
//                            openResume();
                            SearchScanActivity.this.resumt();
                        }
                    }, 500);
                }
                return false;
            }
        });
        titleItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
    }

    protected void modeInit() {
        if (getHandler() != null) {
            getHandler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    changeScanMode(DecoderMode.Zxing);
                }
            }, 1000);
        }
    }

    @Override
    protected void initView() {
        super.initView();
        getToolBar().setNavigationIcon(R.mipmap.icon_back);
        getToolBar().setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        setTitle("查一查");
        titleView = (TextView) findViewById(R.id.text);
        GridView tabView = (GridView) findViewById(R.id.grid);
        final ScanItemAdapter tabAdapter = new ScanItemAdapter(getActivity());
        String[] titles = new String[]{"二维码", "唯一码", "箱码", "GS1码"};
        tabView.setNumColumns(titles.length);
        final Map<Integer, String[]> tipMap = new HashMap<>();
        tipMap.put(1, new String[]{"唯一码示例", "无法识别？"});
        tipMap.put(2, new String[]{"箱码示例", "无法识别？"});
        tipMap.put(3, new String[]{"GS1码示例", "无法识别？"});
        int[] icons = new int[]{R.mipmap.icon_qr_normal, R.mipmap.icon_code_1_normal, R.mipmap.icon_code_1_normal, R.mipmap.icon_code_2_normal};
        int[] selectedIcons = new int[]{R.mipmap.icon_qr_press, R.mipmap.icon_code_1_press, R.mipmap.icon_code_1_press, R.mipmap.icon_code_2_press};

        for (int i = 0; i < icons.length; i++) {
            ChooseItem item = new ChooseItem();
            item.setTitle(titles[i]);
            item.setDrawable(icons[i]);
            item.setType(selectedIcons[i]);
            tabAdapter.addItem(item);
        }
        tabView.setAdapter(tabAdapter);
        final TextView tip1 = (TextView) findViewById(R.id.button2);
        final TextView tip2 = (TextView) findViewById(R.id.button3);
        tip1.setOnClickListener(tipListener);
        tip2.setOnClickListener(tipListener);
        initTip(tip1, tip2, tipMap.get(0));
        tabView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                tabAdapter.setChoose(i);
                tabAdapter.notifyDataSetChanged();
                position = i;
                initTip(tip1, tip2, tipMap.get(position));
            }
        });
    }

    private void finishAdd() {

    }

    private void vibrate() {
        Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
        vibrator.vibrate(200);
    }

    @Override
    public void onScanQRCodeSuccess(String result) {
        vibrate();
        scanResult(result);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopPDAScan();
    }


    private void show(String[] values) {
        LinearLayout rootView = (LinearLayout) findViewById(R.id.root);
        rootView.setVisibility(View.VISIBLE);
        LayoutInflater inflater = LayoutInflater.from(getActivity());
        rootView.removeAllViews();
        findViewById(R.id.bar).setVisibility(View.VISIBLE);
        findViewById(R.id.customPanel).setVisibility(View.GONE);
        if (position == 1) {

        } else if (position == 2) {
            final TextView[] tv = ViewTool.setFourItem(inflater, rootView, new String[]{"运单号", pos2Code1});
            tv[1].setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    new FormDialog(getActivity(), new FormDialog.FormListener() {
                        @Override
                        public void okClick(String[] value) {
                            tv[1].setText(value[0]);
                            pos2Code1 = value[0];
                            setBtnEnable(pos2Code1, pos2Code2);
                        }
                    }, "运单号").addView(new String[]{""}, 0, pos2Code1).show();
                }
            });
            final TextView[] tv1 = ViewTool.setFourItem(inflater, rootView, new String[]{"箱号", pos2Code2});
            tv1[1].setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    new FormDialog(getActivity(), new FormDialog.FormListener() {
                        @Override
                        public void okClick(String[] value) {
                            tv1[1].setText(value[0]);
                            pos2Code2 = value[0];
                            setBtnEnable(pos2Code1, pos2Code2);
                        }
                    }, "箱号").addView(new String[]{""}, 0, pos2Code2).show();
                }
            });
            TextView titleView = (TextView) findViewById(R.id.bottom).findViewById(R.id.title);
            titleView.setVisibility(View.GONE);
            TextView btn = (TextView) findViewById(R.id.button1);
            btn.setText("扫描完成");
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            int margin = Utils.convertDIP2PX(getActivity(), 12);
            lp.setMargins(margin, margin, margin, margin);
            btn.setLayoutParams(lp);
            setBtnEnable(pos2Code1, pos2Code2);
            btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    postScan();
                }
            });
        } else {
            if (values == null) {
                values = new String[]{"", "", "", pos3Date, "", ""};
            }
            final TextView[] tv = ViewTool.setFourItem(inflater, rootView, new String[]{"01-[GTIN]", "10-[批号]"}, new String[]{pos3Code1, pos3Code2}, true);
            tv[0].setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    new FormDialog(getActivity(), new FormDialog.FormListener() {
                        @Override
                        public void okClick(String[] value) {
                            tv[0].setText(value[0]);
                            pos3Code1 = value[0];
                            setBtnEnable(pos3Code1, pos3Code2);
                        }
                    }, "GTIN").addView(new String[]{"GTIN"}, 0, pos3Code1).show();
                }
            });
            tv[1].setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    new FormDialog(getActivity(), new FormDialog.FormListener() {
                        @Override
                        public void okClick(String[] value) {
                            tv[1].setText(value[0]);
                            pos3Code2 = value[0];
                            setBtnEnable(pos3Code1, pos3Code2);
                        }
                    }, "批号").addView(new String[]{"批号"}, 0, pos3Code2).show();
                }
            });
            ViewTool.setFourItem(inflater, rootView, new String[]{"11-[生产日期]", "17-[失效日期]"}, new String[]{values[2], values[3]});
            ViewTool.setFourItem(inflater, rootView, new String[]{"20-[变种]", "21-[唯一标识]"}, new String[]{values[4], values[5]});
            TextView titleView = (TextView) findViewById(R.id.bottom).findViewById(R.id.title);
            titleView.setVisibility(View.GONE);
            TextView btn = (TextView) findViewById(R.id.button1);
            btn.setText("扫描完成");
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            int margin = Utils.convertDIP2PX(getActivity(), 12);
            lp.setMargins(margin, margin, margin, margin);
            btn.setLayoutParams(lp);
            setBtnEnable(pos3Code1, pos3Code2);
            btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    postScan();
                }
            });
        }

    }

    private void query() {
        if (position == 0) {
            //TODO 发票详情

        } else {
            //产品详情
            postScan();
        }
//        resetCode();
    }

    private void setBtnEnable(String value1, String value2) {
        if (TextUtils.isEmpty(value1) || TextUtils.isEmpty(value2)) {
            findViewById(R.id.bar).setEnabled(false);
            findViewById(R.id.bar).setBackgroundColor(ContextCompat.getColor(getContext(), R.color.text_gray));
        } else {
            findViewById(R.id.bar).setEnabled(true);
            findViewById(R.id.bar).setBackgroundResource(R.drawable.shape_corner);
        }
        findViewById(R.id.bar).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                query();
            }
        });
    }

    private void scanResult(String code) {
        if (position == 0) {
            ticketQuery(code);
        } else if (position == 1) {
            pos1Code = code;
            query();
        } else if (position == 2) {
            if (code.length() == 10) {
                pos2Code1 = code;
            } else if (code.length() == 4) {
                pos2Code2 = code;
            }
            show(null);
            startSpot();
        } else {
            if (code.startsWith("01") && code.length() >= 16) {
                pos3Code1 = code.substring(2, 16);
            } else if (code.startsWith("17")) {
                if (code.length() > "1719013110".length()) {
                    pos3Code2 = code.substring("1719013110".length());
                    pos3Date = code.substring(2, 8);
                }
            }
            show(null);
            startSpot();
        }
    }

    private void resetCode() {
        pos1Code = "";
        pos2Code1 = "";
        pos2Code2 = "";
        pos3Code1 = "";
        pos3Code2 = "";
    }

    private void postScan() {
        showLoadImg();
        Map<String, String> param = new HashMap<>();
//        param.put("type", "2");
        if (position == 1) {
            param.put("serialNumber", pos1Code);
        } else if (position == 2) {
            param.put("packageNumber", pos2Code2);
            param.put("deliveryNumber", pos2Code1);
        } else {
            param.put("gtin", pos3Code1);
            param.put("lots", pos3Code2);
        }
        getHttpClient().post().url(Constant.SCAN_PRODUCT).params(Constant.makeParam(param)).build().execute(new StringCallback() {

            @Override
            public void onError(Call call, Exception e, int i) {
                dismissLoadImg();
                startSpot();
            }

            @Override
            public void onResponse(String s, int i) {
                try {
                    if (getActivity() == null) {
                        return;
                    }
                    dismissLoadImg();
                    startSpot();
//                    System.out.println(s);
                    JSONObject data = new JSONObject(s);
                    String code = "";
                    String msg = "";
                    JSONArray array = null;
                    if (data.has("result")) {
                        code = data.getJSONObject("result").getString("code");
                        msg = data.getJSONObject("result").has("msg") ? data.getJSONObject("result").getString("msg") : "";
                        array = data.getJSONObject("result").has("objList") ? data.getJSONObject("result").getJSONArray("objList") : new JSONArray();
                    } else {
                        code = data.getString("code");
                        msg = data.has("msg") ? data.getString("msg") : "";
                        array = data.has("objList") ? data.getJSONArray("objList") : new JSONArray();
                    }

                    if (!"1".endsWith(code)) {
                        Utils.showToast(getActivity(), msg);
                        return;
                    }
//                    if (position == 0) {
//                        parseOne(data.getJSONObject("result").getJSONArray("objList"));
//                    } else if (position == 1) {
//                        parseBox();
//                    } else {
//                        parseGS();
//                    }
                    if (array.length() == 0) {
                        Utils.showToast(getContext(), "产品不存在");
                        return;
                    }
                    parseOne(array);
                } catch (Exception e) {
                    Utils.showToast(getActivity(), "解析数据失败！");
                }
            }
        });
//        resetCode();
    }

    private void parseOne(JSONArray array) throws JSONException {
        List<ProductList.ProductItem> list = new ArrayList<>();
        ProductList.ProductItem item = null;
        for (int i = 0; i < array.length(); i++) {
            JSONObject obj = array.getJSONObject(i);
            item = new ProductList.ProductItem();
            item.setMaterialName(obj.getString("materialName"));
            item.setMaterialNumber(obj.getString("materialNumber"));
            item.setSerialNumber(obj.getString("serialNumber"));
            item.setLots(obj.getString("batchNumber"));
            item.setSubBU(obj.getString("subBU"));
            item.setUom(obj.getString("saleUnit"));
            item.setQty(obj.getString("qty"));
            item.setNowqty(obj.getString("qty"));
            item.setProductId(obj.getString("productId"));
            item.setExpDate(obj.getString("expDate"));
            item.setDomDate(obj.getString("dom_date"));
            item.setDistCode(obj.getString("distCode"));
            item.setDistName(obj.getString("distName"));
            item.setCusName(obj.getString("cusName"));
            list.add(item);
        }
        if (list.size() == 1) {
            Bundle bundle = new Bundle();
            bundle.putSerializable("model", list.get(0));
            bundle.putInt("type", 1);
            FragmentUtil.navigateToInNewActivity(getActivity(), ProductInfoFragment.class, bundle);
        } else if (list.size() > 1) {
            Bundle bundle = new Bundle();
            ProductList mList = new ProductList();
            mList.setProductList(list);
            bundle.putSerializable("model", mList);
            FragmentUtil.navigateToInNewActivity(getActivity(), ProductListFragment.class, bundle);
        } else {
            Utils.showToast(getActivity(), "未查询到结果！");
        }
    }

    private void ticketQuery(String result) {
        try {
            String[] array = result.split(",");
            if (array.length >= 8) {
                InvoiceList.Invoice invoice = new InvoiceList.Invoice();
                invoice.setInCode(array[2]);
                invoice.setInNO(array[3]);
                invoice.setNonetaxTotal(array[4]);
                invoice.setInDate(array[5]);
                invoice.setVerifyCode(array[6]);
                Bundle bundle = new Bundle();
                bundle.putSerializable("model", invoice);
                FragmentUtil.navigateToInNewActivity(getActivity(), TicketDetailFragment.class, bundle);
//                showLoadImg();
//                Map<String, String> param = new HashMap<>();
//                param.put("inNo", array[3]);
//                getHttpClient().post().url(Constant.INVOICE_DETAIL).params(Constant.makeParam(param)).build().execute(new StringCallback() {
//                    @Override
//                    public void onError(Call call, Exception e, int i) {
//                        Utils.showToast(getContext(), R.string.server_error);
//                        startSpot();
//                    }
//
//                    @Override
//                    public void onResponse(String s, int i) {
//                        try {
//                            System.out.println(s);
//                        } catch (Exception e) {
//                            Utils.showToast(getContext(), "识别发票二维码失败!");
//                        } finally {
//                            dismissLoadImg();
//                            startSpot();
//                        }
//                    }
//                });
                startSpot();
            } else {
                startSpot();
            }
        } catch (Exception e) {
            Utils.showToast(this, "识别发票二维码失败!");
            startSpot();
        }
    }

    private void PDAScan() {
        Intent startIntent = new Intent("nlscan.action.SCANNER_TRIG");
        startIntent.putExtra("SCAN_TIMEOUT", 4);
        sendBroadcast(startIntent);

        Intent intent = new Intent("ACTION_BAR_SCANCFG");
        intent.putExtra("EXTRA_SCAN_MODE", 3);

//        TODO
//        intent.putExtra("EXTRA_TRIG_MODE", 1);
//        intent.putExtra("EXTRA_SCAN_NOTY_SND", 1);
//
//                TODO
//        intent.putExtra("EXTRA_SCAN_MODE", 1);
        intent.putExtra("EXTRA_SCAN_AUTOENT", 1);

        sendBroadcast(intent);

    }

    private void stopPDAScan() {
        Intent startIntent = new Intent("nlscan.action.SCANNER_TRIG");
        startIntent.putExtra("SCAN_TIMEOUT", 4);
        sendBroadcast(startIntent);
        Intent stopIntent = new Intent("nlscan.action.STOP_SCAN");
        sendBroadcast(stopIntent);
    }

    public void startSpot() {
        if (pdaFlag) {
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    PDAScan();
                }
            }, 1000);
            return;
        }
        super.startSpot();
    }

}
